package cn.sinata.wanglin.neighbor.activity;

import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.hyphenate.easeui.EaseConstant;
import com.xilada.xldutils.activitys.TitleActivity;
import com.xilada.xldutils.adapter.BaseRecyclerAdapter;
import com.xilada.xldutils.utils.ActivityUtil;
import com.xilada.xldutils.utils.SharedPreferencesUtils;
import com.xilada.xldutils.utils.Utils;

import java.util.ArrayList;
import java.util.Locale;

import butterknife.BindView;
import butterknife.OnClick;
import cn.sinata.wanglin.R;
import cn.sinata.wanglin.adapter.MemberAdapter;
import cn.sinata.wanglin.commonutils.Constant;
import cn.sinata.wanglin.db.dao.GroupDao;
import cn.sinata.wanglin.db.dao.GroupUserDao;
import cn.sinata.wanglin.db.dao.UserDao;
import cn.sinata.wanglin.model.Group;
import cn.sinata.wanglin.model.Member;
import cn.sinata.wanglin.net.HttpManager;
import cn.sinata.wanglin.net.model.util.ResultDataSubscriber;
import cn.sinata.wanglin.utils.ImageUtil;
import cn.sinata.wanglin.village.activity.AllUserInfoActivity;


public class GroupInfoActivity extends TitleActivity {
    @BindView(R.id.image)
    SimpleDraweeView imageView;
    @BindView(R.id.tv_member_count)
    TextView tv_member_count;
    @BindView(R.id.member_list)
    RecyclerView member_list;
    @BindView(R.id.ownerHeadView)
    SimpleDraweeView ownerHeadView;
    @BindView(R.id.tv_owner_name)
    TextView tv_owner_name;
    @BindView(R.id.tv_owner_info)
    TextView tv_owner_info;
    @BindView(R.id.tv_tags)
    TextView tv_tags;
    @BindView(R.id.tv_group_description)
    TextView tv_group_description;
    @BindView(R.id.tv_action)
    TextView tv_action;
    @BindView(R.id.tv_action1)
    TextView tv_action1;
    private String userId;
    private String groupId;
    private String groupAccount;//群组环信帐号
    private String groupName;
    private String groupUrl;
    private String userNick;
    private String userHead;
    private Group mGroup;
    private int state = -1;
    private int msgStatus ;
    private MemberAdapter memberAdapter;
    private ArrayList<Member> members = new ArrayList<>();
    private boolean isOwner = false;
    private boolean isEdit = false;
    private int type = 0;

    @Override
    protected int setContentId() {
        return R.layout.activity_group_info;
    }

    @Override
    protected void initView() {
        super.initView();

        userId = SharedPreferencesUtils.getString(Constant.SP_USERID);
        groupName = getIntent().getStringExtra("name");
        type = getIntent().getIntExtra("type",0);
        if (type == 1) {
            groupAccount = getIntent().getStringExtra("id");
        } else {
            groupId = getIntent().getStringExtra("id");
        }

        memberAdapter = new MemberAdapter(members);
        member_list.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL,false));
        member_list.setHasFixedSize(true);
        member_list.setAdapter(memberAdapter);
        memberAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                ActivityUtil.create(mContext)
                        .go(AllUserInfoActivity.class)
                        .put("friendID",members.get(position).getUserID())
                        .start();
            }
        });
        setTitle(groupName);
        showDialog();
        getGroupInfo();
    }

    void getGroupInfo(){
        String id = groupId;
        if (type == 1) {
            id = groupAccount;
        }
        HttpManager.groupInfo(userId,id,type)
                .subscribe(new ResultDataSubscriber<Group>(this) {
                    @Override
                    public void onSuccess(String msg, Group group) {
                        mGroup = group;
                        if (type == 1) {
                            groupId = group.getId();
                        }
                        isOwner = mGroup.getUserID().equals(userId);
                        setTitle(group.getGroupName());
                        groupAccount = group.getGroupAccount();
                        groupUrl = group.getGroupImg();
//                        //是群主
//                        if (userId.equals(group.getUserID())) {
//                            userNick = group.getGroupNickName();
//                        } else {
                        userNick = group.getOtherNickName();
                        msgStatus = group.getMsgStatus();
//                        }
                        imageView.setImageURI(ImageUtil.parseImageUri(group.getGroupImg()));
                        tv_member_count.setText(String.format(Locale.CHINA,"群成员\n%s",group.getMemberList()==null?0:group.getMemberList().size()));
                        ownerHeadView.setImageURI(ImageUtil.parseImageUri(group.getHeadUrl()));
                        tv_owner_name.setText(group.getGroupNickName());
                        tv_owner_info.setText("来自 "+group.getHousingName());
                        tv_tags.setText(group.getGroupLable());
                        tv_group_description.setText(group.getGroupInfo());
                        state = group.getApplyStatus();
                        tv_action.setEnabled(true);

                        if (state == 1) {
                            tv_action.setText("进入群聊");
                            tv_action1.setVisibility(View.VISIBLE);
                        } else if (state == 3 || state == 2) {
                            tv_action.setText("申请加入");
                            tv_action1.setVisibility(View.GONE);
                        } else if (state == 0) {
                            tv_action.setText("申请中");
                            tv_action.setEnabled(false);
                            tv_action1.setVisibility(View.GONE);
                        }

                        members.clear();
                        members.addAll(group.getMemberList());
                        memberAdapter.notifyDataSetChanged();
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Utils.systemErr("----"+resultCode+"====="+requestCode);
        if (resultCode == RESULT_OK) {
            if (requestCode == 10) {
                showDialog();
                getGroupInfo();
                isEdit = true;
            } else if (requestCode == 16) {
                isEdit = true;
                showDialog();
                getGroupInfo();
            } else if (requestCode == 21) {
                showDialog();
                getGroupInfo();
                isEdit = true;
            }
        } else if (resultCode == Constant.ResultCode_QUITE) {
            //反正覆盖code
            isEdit = false;
            setResult(Constant.ResultCode_QUITE);
            finish();
        }
    }

    @Override
    public void finish() {
        if (isEdit) {
            setResult(RESULT_OK);
        }
        super.finish();
    }

    @OnClick({R.id.tv_action,R.id.tv_action1,R.id.tv_member_list})
    void onViewClick(View view) {
        switch (view.getId()) {
            case R.id.tv_action:
                if (state == 1) {

                    //从聊天进入的
                    if (type == 1) {
                        finish();
                    } else {
                        //存储群组头像昵称。
                        UserDao.getInstance(this).saveUser(groupAccount,groupName,groupUrl);
                        String account = SharedPreferencesUtils.getString(Constant.SP_IM_ACCOUNT);
                        String headUrl = SharedPreferencesUtils.getString(Constant.SP_HEADURL);
                        //存储当前用户在群组的昵称和头像
                        GroupUserDao.getInstance(this).saveGroupUser(groupAccount,account,userNick,headUrl);
                        //存储群信息
                        GroupDao.getInstance(this).saveGroup(userId,mGroup);

                        ActivityUtil.create(this)
                                .go(ChatActivity.class)
                                .put(EaseConstant.EXTRA_CHAT_TYPE,EaseConstant.CHATTYPE_GROUP)
                                .put(EaseConstant.EXTRA_USER_ID,groupAccount)
                                .start();
                    }
                } else if (state == 3 || state == 2) {
                    ActivityUtil.create(this)
                            .go(ApplyFriendOrGroupActivity.class)
                            .put("type",1)
                            .put("id",groupId)
                            .put("account",groupAccount)
                            .startForResult(21);
                }

                break;
            case R.id.tv_action1:

                ActivityUtil.create(this)
                        .go(GroupSettingActivity.class)
                        .put("groupNick",userNick)
                        .put("id",groupId)
                        .put("account",groupAccount)
                        .put("status",msgStatus)
                        .put("name",mGroup.getGroupName())
                        .put("image",mGroup.getGroupImg())
                        .put("content",mGroup.getGroupInfo())
                        .put("isOwner",isOwner)
                        .startForResult(10);
                break;
            case R.id.tv_member_list:
                ActivityUtil.create(this)
                        .go(GroupMembersActivity.class)
                        .put("isOwner",isOwner)
                        .put("account",groupAccount)
                        .put("id",groupId)
                        .putParcelableList("data",members)
                        .startForResult(16);
                break;
        }
    }
}
